<template>
    <div>
        <!--        <m-filter placeholder="关键字搜索" searchKey="title" @search="searchTable">-->
        <m-filter placeholder="关键字搜索" searchKey="">
            <template slot="search-form">
                <span>
                    年度:
                    <a-select
                        :default-value="searchParams.applyYear"
                        v-model="searchParams.applyYear"
                        @change="onYearChange"
                    >
                        <a-select-option :value="item" v-for="item in yearList" :key="item">
                            {{ item }}
                        </a-select-option>
                    </a-select>
                </span>
                <a-divider type="vertical" />
                <a-button icon="plus" type="primary" @click="openRowOperateModal()">新增根分类</a-button>
                <a-divider type="vertical" />
                <span>评价总分: {{ totalScore }}</span>
                <a-divider type="vertical" />
                <span>自评分: {{ evaluationScore }}</span>
                <a-divider type="vertical" />
                <span>鼓励分: {{ encourageScore }}</span>
            </template>
        </m-filter>
        <div class="table">
            <a-table
                rowKey="id"
                :columns="columns"
                :loading="tableLoading"
                :data-source="tableData"
                class="no-pagination-table"
                :scroll="{ y: true }"
                :pagination="false"
            >
                <template slot="name" slot-scope="text, record">
                    <a @click="openDetailModal(record)">
                        {{ record.getSnPath() }}、{{ text }} ({{ record.getSumScore() }}分)
                    </a>
                </template>
                <template slot="operate" slot-scope="text, record">
                    <span class="primary-color" v-if="isCanAddChild(record)" @click="openSubOperateModal(record)">
                        添加下级
                    </span>
                    <a-divider type="vertical" v-if="isCanAddChild(record)" />
                    <span class="primary-color" @click="openRowOperateModal(record)">编辑</span>
                    <a-divider type="vertical" />
                    <a-popconfirm title="确定删除吗?" ok-text="是" cancel-text="否" @confirm="del(record.id)">
                        <span class="danger-color">删除</span>
                    </a-popconfirm>
                </template>
            </a-table>
        </div>
        <operateModal
            v-if="isOpenOperateModal"
            :isShowModal.sync="isOpenOperateModal"
            :currRow="currRow"
            :apply-year="searchParams.applyYear"
            :parentRow="parentRow"
            :enterpriseId="currSelectedTreeId"
            @updateData="getTableData"
        />
    </div>
</template>

<script>
import operateModal from './modal/index.vue'
import { selfEvaluationTemplateRestApi } from '../../../common/api/setting'
import MFilter from '../../../components/filter'
import moment from 'moment'

export default {
    name: 'selfEvaluationTemplate',
    components: {
        MFilter,
        operateModal,
    },
    data() {
        let nowYear = this.$moment().year() + 2
        let yearList = []

        for (var i = nowYear; i >= 2020; i--) {
            yearList.push(i)
        }

        return {
            yearList,
            // table
            columns: [
                {
                    title: '评价分类/评价内容',
                    key: 'name',
                    dataIndex: 'name',
                    scopedSlots: { customRender: 'name' },
                },
                {
                    title: '评价操作指南',
                    key: 'operationGuide',
                    dataIndex: 'operationGuide',
                },
                {
                    title: '分值',
                    key: 'score',
                    width: 100,
                    dataIndex: 'score',
                },
                {
                    title: '排序',
                    key: 'sortNum',
                    width: 100,
                    dataIndex: 'sortNum',
                },
                {
                    title: '操作',
                    dataIndex: 'operate',
                    scopedSlots: { customRender: 'operate' },
                    width: 200,
                },
            ],
            remoteTableData: [],
            tableData: [],
            tableLoading: false,
            currRow: undefined,
            parentRow: undefined,
            // modal
            isOpenOperateModal: false,
            //enterprise tree
            currSelectedTreeId: '',

            searchParams: { applyYear: moment().format('yyyy') },
        }
    },
    computed: {
        totalScore() {
            if (this.tableData) {
                return _.sum(this.tableData.map(n => n.getSumScore()))
            }
            return 0
        },
        encourageScore() {
            if (this.tableData) {
                return _.sum(this.tableData.map(n => n.getEncourageScore()))
            }
            return 0
        },
        evaluationScore() {
            return this.totalScore - this.encourageScore
        },
    },
    mounted() {
        this.getTableData()
    },
    methods: {
        isCanAddChild(rec) {
            return rec.level < 4
        },
        async onYearChange(v) {
            await this.getTableData()
        },
        async del(id) {
            const res = await selfEvaluationTemplateRestApi.del({ id })
            res.code == 200 ? this.$message.success(`删除评价成功`) : this.$message.error(`删除评价失败`)
            await this.getTableData()
        },
        openRowOperateModal(row) {
            this.currRow = row
            this.parentRow = null
            this.isOpenOperateModal = true
        },
        openSubOperateModal(row) {
            this.currRow = null
            this.parentRow = row
            this.isOpenOperateModal = true
        },
        openDetailModal(row) {
            this.currRow = row
            this.isOpenOperateModal = true
        },
        async getTableData() {
            this.tableLoading = true
            let res
            try {
                res = await selfEvaluationTemplateRestApi.get(this.searchParams)
                if (res.code == 200) {
                    this.remoteTableData = res.data
                    this.tableData = this.buildTree(res.data, 1)

                    console.log(this.tableData)
                }
            } catch (e) {
                console.log(e)
            }
            this.tableLoading = false
        },
        searchTable(params) {
            Object.assign(this.searchParams, params)
            clearTimeout(this._inputSearchTimer)
            this._inputSearchTimer = setTimeout(() => {
                this.getTableData()
            }, 600)
        },
        onCreateBtnClick() {},
        buildTree(data, level, parentId) {
            let res = []

            if (parentId) {
                res = data.filter(n => n.level == level && n.parentId == parentId)
            } else {
                res = data.filter(n => n.level == level)
            }

            res = res.sort((a, b) => a.sortNum - b.sortNum)

            res.forEach((n, i) => {
                let innerChildren = this.buildTree(data, level + 1, n.id)

                if (innerChildren && innerChildren.length) {
                    n.children = innerChildren
                    n.leaf = false
                } else {
                    n.leaf = true
                }

                n.sn = i + 1
                n.parent = data.filter(n => n.id == parentId)[0]
                n.getSnPath = () => {
                    if (n.parent) {
                        return [n.parent.getSnPath(), n.sn].join('-')
                    }
                    return n.sn
                }
                n.getSumScore = () => {
                    let result
                    if (n.children) {
                        result = _.sum(n.children.map(m => m.getSumScore()))
                    } else {
                        result = n.score || 0
                    }
                    return +result.toFixed(2)
                }

                n.getEncourageScore = () => {
                    if (n.children) {
                        return _.sum(n.children.map(m => m.getEncourageScore()))
                    } else {
                        if (n.isEncourage) {
                            return n.score || 0
                        }
                        return 0
                    }
                }
            })

            return res
        },
        buildLevelPath(level) {
            var res = []
            for (let i = 1; i <= level; i++) {
                res.push(i)
            }
            return res.join('-')
        },
    },
}
</script>

<style lang="scss" scoped></style>
